package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.BaseDocumentAddDto;
import com.kaili.basic.pojo.dto.FacilityVersionAddDto;
import com.kaili.basic.pojo.dto.FacilityVersionDto;
import com.kaili.basic.pojo.entity.BaseDocumentEntity;
import com.kaili.basic.pojo.entity.FacilityVersion;
import com.kaili.basic.pojo.entity.FacilityVersionQuery;
import com.kaili.basic.pojo.vo.FacilityVersionVO;
import com.kaili.basic.service.BaseDocumentService;
import com.kaili.basic.service.IFacilityVersionService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.fastdfs.UploadController;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.LoginDetailUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc: 版本设置控制类
 * @author: PF12Z08Z
 * @Time: 2019/7/25 18:54
 * @Copyright: © 2018 杭州凯立通信有限公司 版权所有
 * @Warning: 本内容仅限于公司内部传阅, 禁止外泄或用于其它商业目的
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "版本设置", description = "版本设置相关API")
@RestController
public class FacilityVersionController {

    @Autowired
    private IFacilityVersionService facilityVersionService;
    @Autowired
    private BaseDocumentService baseDocumentService;

    /**
    *自动生成版本编码
    *@author:linjian
    *@Time:2019/7/25 18:58
    *@param
    *@return
    */
    @ApiOperation(value = "自动生成公司编码", notes = "自动生成公司编码")
    @PostMapping("/facility/versionCode")
    public String autoCreateCompanyCode(){

        //在跳转到版本设置页面的时候，首先查询是否存在可以使用的编码，若不存在，就自动生成返回给前端
        String code =  facilityVersionService.getUsableCode();
        if (null == code){
            Map<String,Object> timeMap = new HashMap<>();
            Date createdTime = new Date();
            Date optTime = new Date();
            timeMap.put("createdTime",createdTime);
            timeMap.put("optTime",optTime);
            facilityVersionService.createdVersionCode(timeMap);
            code = facilityVersionService.getUsableCode();
        }
        String zero = "0";
        if (code.length()<9){
            int index = 9 - code.length();
            for (int i = 0;i<index;i++){
                code = zero+code;
            }
        }
        return code;
    }

    /**
    *查询所有版本
    *@author:linjian
    *@Time:2019/7/25 19:37
    *@param null
    *@return
    */
    @ApiOperation(value = "查询所有版本信息", notes = "查询所有版本信息")
    @GetMapping("/facility/versions")
    public List<FacilityVersion> queryFacilityVersion(){
        List<FacilityVersion> list = facilityVersionService.queryAllVersion();
        return list;
    }

    /*
    *按条件查询版本
    *@author:linjian
    *@Time:2019/7/25 19:43
    *@param null
    *@return
    */
    @ApiOperation(value = "分页查询所有版本信息", notes = "分页查询所有版本信息")
    @GetMapping("/facility")
    public Page<FacilityVersionVO> queryFacilityVersionByConditions(@ModelAttribute FacilityVersionDto dto){
        Page<FacilityVersionVO> page = facilityVersionService.queryFacilityVersionByConditions(new Page<FacilityVersionVO>(dto.getPage(), dto.getPageSize()),dto);
        return page;
    }

    /**
    *新增版本
    *@author:linjian
    *@Time:2019/7/25 20:19
    *@param null
    *@return
    */
    @ApiOperation(value = "新增版本", notes = "新增版本")
    @PostMapping("/facility/addVersion")
    public RestStatus addFacilityVersion(@RequestBody FacilityVersionAddDto dto){

        FacilityVersionVO facilityVersion = new FacilityVersionVO();
        BeanUtils.copyProperties(dto,facilityVersion);
        //根据版本编码查询是否已经存在了
        FacilityVersion facility = facilityVersionService.queryVersionByCode(dto.getVersionCode());
        if (null != facility){
            return CommonStatus.ADD_DEFEAT;
        }
        String resultCode =  replaceCode(facilityVersion.getVersionCode());
        if("999999999".equals(resultCode)){
            return CommonStatus.ADD_CODE_USED;
        }
        //新增版本，将自动生成的版本编码设为正在使用状态
        facilityVersionService.updateVersionCodeStatusUsing(resultCode);
        //添加人
        Long createBy = LoginDetailUtils.getCurrentEmployeeId().longValue();
        facilityVersion.setCreatedBy(createBy);
        facilityVersion.setCreatedTime(new Date());
        int result =  facilityVersionService.addFacilityVersion(facilityVersion);
        if (result == 1){
            //新增成功，将编码使用状态变更为已使用
            facilityVersionService.updateVersionCodeStatusUsed(resultCode);
        }else{
            //新增失败，将编码使用状态变为未使用
            facilityVersionService.updateVersionCodeStatusUsing(resultCode);
        }
        return CommonStatus.ADD_OK;
    }

    /**
    *文件上传
    *@author:linjian
    *@Time:2019/7/29 10:43
    *@param null
    *@return
    */
    @ApiOperation(value = "新增文档下发设置")
    @PostMapping("/facility/down")
    public RestStatus addDocument(BaseDocumentAddDto dto, @RequestParam("file") MultipartFile file){
        BaseDocumentEntity entity = getFormData(dto,file);
        // 表示服务器下发
        entity.setPattern("1");
        // 如果结束时间不为空，表示是下发设置 ，否则表示设备主动上传
        if(entity.getEndTime() != null){
            entity.setWay("2");
        } else {
            entity.setWay("1");
        }
        baseDocumentService.addDocument(entity);
        return CommonStatus.ADD_OK;
    }

    private BaseDocumentEntity getFormData(BaseDocumentAddDto dto,MultipartFile file) {
        BaseDocumentEntity entity = new BaseDocumentEntity();
        BeanUtils.copyProperties(dto,entity);
        try {
            if (file != null && file.getSize() != 0) {
                String path = UploadController.saveFile(file);
                entity.setFileUrl(path);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return entity;
    }

    public String replaceCode(String versionCode){
        Long code = Long.parseLong(versionCode);
        return code.toString();
    }
}
